package com.xy.demo.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.xy.demo.Util.Constant;
import com.xy.demo.Util.Util;
import com.xy.demo.excel.ExcelOne;
import com.xy.demo.mapper.mysql.ExcelOneMapper;
import lombok.extern.slf4j.Slf4j;


import java.util.List;



@Slf4j
public class DemoOneListener extends AnalysisEventListener<ExcelOne> {

    private ExcelOneMapper excelOneMapper ;

   /* public DemoOneListener(ExcelOneMapper excelOneMapper){
        this.excelOneMapper = excelOneMapper;
    }*/


    /**
     *  每隔10条数据  处理完后  清理list  便于内存回收
     */
    private static final int BATCH_COUNT = Constant.ExcelBatchCount.BATCH_COUNT_TEN;

    /**
     * 缓存的数据
     */
    private List<ExcelOne> cacheDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    /**
     *  每条数据都调用
     * @param excelOne  每一条数据
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelOne excelOne, AnalysisContext analysisContext) {
        System.out.println("解析到一条数据{} "+ JSON.toJSONString(excelOne));
         cacheDataList.add(excelOne);
         //达到BATCH_COUNT了，需要去数据库处理一下
         if(cacheDataList.size()>=BATCH_COUNT){
             saveData();
             //处理完成 清理list
             cacheDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
         }
    }

    /**
     *  数据解析过后调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();  //二次处理数据   确保数据处理完成
        System.out.println("所有数据解析完成");
    }

    public void saveData(){
        System.out.println("{}条数据，开始处理数据！ "+cacheDataList.size());
        cacheDataList.forEach(e->{
            System.out.println("处理数据："+e.toString());
           //System.out.println("输出数据日期："+ Util.formatDate(e.getFieldSecond(),"YYYY-MM-DD HH:mm:ss"));
        });
        System.out.println("数据处理完成");
    }
}
